import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { getMessageInfo } from './status'

interface BaseReponse<T = any>{
    code: number | string,
    message: string,
    data: T
}

const service = axios.create({
    baseURL: import.meta.env.VITE_APP_USE_MOCK ? import.meta.env.VITE_APP_MOCK_BASEURL:import.meta.env.VITE_APP_API_BASEURL,
    timeout: 15000
})
// axios实例拦截请求
service.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    return config
},(error:AxiosError) => {
    return Promise.reject(error)
})
// axios实例拦截响应
service.interceptors.response.use((response:AxiosResponse) => {
    if(response.status === 200) {
        return response.data
    }
    ElMessage({
        message: getMessageInfo(response.status),
        type: "error"
    })
    return response.data    
},(error:any) =>{
    const {response} = error
    if(response) {
        ElMessage({
            message: getMessageInfo(response.status),
            type: "error"
        })
        return Promise.reject(response.data)
    }
    ElMessage({
        message: "网络连接异常，请稍后再试!",
        type: "error"
    })
});

const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => {
    const conf = config
    return new Promise((resolve,reject) => {
        service.request<any, AxiosResponse<BaseReponse>>(conf).then((res:AxiosResponse<BaseReponse>) => {
            const data = res.data;
            if(data.code != 0){
                ElMessage({
                    message:data.message,
                    type: "error"
                })
                reject(data.message)
            } else {
                ElMessage({
                    message: data.message,
                    type:"success"
                })
                resolve(data.data as T)
            }
        })
    })
}

export function get<T = any, U = any>(config: AxiosRequestConfig,url:string,params?: U): Promise<T>{
    return requestInstance({...config,url,method:"POST",params: params})
}

export function post<T = any, U = any>(config: AxiosRequestConfig,url:string,data:U):Promise<T>{
    return requestInstance({...config,url,method:"POST",data: data})
}

export function put<T = any,U = any>(config:AxiosRequestConfig,url:string,data:U):Promise<T>{
    return requestInstance({...config,url,method:"PUT",data: data})
}
export function del<T = any,U = any>(config:AxiosRequestConfig,url:string,data:U):Promise<T>{
    return requestInstance({...config,url,method:"DELETE",data: data})
}

export default service;



